const express = require("express"); // 引入express框架
const cors = require("cors"); // 引入CORS中间件
const db = require("./db"); // 引入数据库连接
const app = express();

// 中间件配置
app.use(express.json());
// 允许所有域名访问
app.use(cors());

// 路由文件导入
const userRoutes = require('./routes/userRoutes');
const wordRoutes = require('./routes/wordRoutes');

// API路由挂载
app.use('/api/users', userRoutes);
app.use('/api/words', wordRoutes);

// 兼容老接口 - 单词转换函数
function transformWordDataToNewData(wordData) {
  const total = wordData.length;
  const list = wordData.map(item => {
    return {
      id: item.id,           // 使用 id
      word: item.word,
      phonetic_symbol: item.phonetic_symbol,
      mean: item.mean,
      initial: item.initial,
      created_at: item.created_at  // 添加创建时间字段
    };
  });
  return {
    code: 0,
    data: {
      total: total,
      pageSize: 10,
      totalPage: Math.ceil(total / 10),
      currPage: 1,
      list: list
    }
  };
}

// 兼容老接口 - 获取所有单词
app.get('/', (req, res) => {
  console.log('收到获取所有单词请求');
  
  const sql = "SELECT * FROM words";
  db.query(sql, (err, result) => {   
    if (err) {
      console.error('数据库错误详情:', err);
      return res.status(500).send({ 
        state: 1, 
        message: "查询失败", 
        error: err.message,
        data: null 
      });
    }
    
    console.log('查询结果:', result);
    const transformedData = transformWordDataToNewData(result);
    res.send(transformedData);
  });
});

// 兼容老接口 - 获取单个单词
app.get('/word/:id', (req, res) => {
  const id = req.params.id;
  console.log('收到获取单词详情请求，ID:', id);
  
  const sql = 'SELECT word, mean FROM words WHERE id = ?';
  db.query(sql, [id], (err, result) => {
    if (err) {
      console.log(err);
      return res.status(500).send({ state: 1, message: '查询失败', data: null });
    }
    if (result.length === 0) {
      return res.status(404).send({ state: 1, message: '未找到对应的单词', data: null });
    }
    const wordData = result[0];
    res.send({ word: wordData.word, mean: wordData.mean });
  });
});

// 处理所有未匹配的路由
app.all('*', (req, res) => {
  res.status(404)
  res.send('你要访问的资源路径不存在');
});

// 服务器配置
const PORT = process.env.PORT || 3002;
const HOST = '0.0.0.0';  // 监听所有网络接口

// 启动服务器
app.listen(PORT, HOST, () => {
  console.log(`服务器运行在端口 ${PORT}`);
});